package com.sxygsj.baselibrary.utils

import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date

object TimeUtils {
    val sdf = SimpleDateFormat("yyyy-MM-dd")
    val dateSdf =SimpleDateFormat("yyyy-MM-dd HH:mm")


    fun getFrontSdf(pattern:String):SimpleDateFormat{
        return SimpleDateFormat(pattern)
    }
    fun getBeforeSdf(pattern:String):SimpleDateFormat{
        return SimpleDateFormat(pattern)
    }
    /**
     * @Description: [时间格式转换]
     * @Param: frontPattern：转换前的时间格式；beforePattern：转换后的时间格式；time：要转换的时间
     * @Return: formatTime：转换后的时间
     */;
    fun timeFormat(frontPattern:String,beforePattern:String,time: String?): String? {
        if (time == null) {
            return null
        }
        var formatTime: String? = null
        try {
            val frontDate= getFrontSdf(frontPattern).parse(time)
            formatTime = getBeforeSdf(beforePattern).format(frontDate)

        } catch (e: ParseException) {
            e.printStackTrace()
            return time
        }

        return formatTime
    }

    /**
     * 毫秒时间转换成字符串,指定格式 默认为"yyyy-MM-dd HH:mm:ss"
     *
     * @param time   时间
     * @param format 时间格式
     */
    @JvmOverloads
    fun dateToString(time: Long, format: String = "yyyy.MM.dd HH:mm"): String {
        val date = Date(time)
        val simpleDateFormat = SimpleDateFormat(format)
        return simpleDateFormat.format(date)
    }


    /**
     *
     * 秒转换为时间字符
     */
    fun secondToString(time:Int):String{
        var num: Int
        var second=time%60
        var minute: Int
        var hour: Int
        var res ="$second 秒"
        num=time-second
        if(num>0){
            num/=60
            minute=num%60
            res= "$minute 分$res"
            num-=minute
            if(num>0){
                hour=num/60
                res="$hour 小时$res"
            }

        }
        return res
    }

    /**
     * @Description: [增加时间]
     * @Param: 增加的类型，要增加的时间，增加的时长
     * @Return:
     */
    fun timeAdd(type: Int, startTime: Date, addTime: Int): Date {
        var endTime: String? = null
        val calendar = Calendar.getInstance()
        try {
            calendar.time = startTime
        } catch (e: ParseException) {
            e.printStackTrace()
        }

        calendar.add(type, addTime)
        return calendar.time
    }
}

